package com.ldwx.center.service.impl;

import com.ldwx.center.common.entity.Result;
import com.ldwx.center.common.entity.StatusCode;
import com.ldwx.center.dao.RecruitDao;
import com.ldwx.center.dao.TaskDao;
import com.ldwx.center.model.Recruit;
import com.ldwx.center.model.Task;
import com.ldwx.center.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService{
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private RecruitDao recruitDao;
    @Override
    public Result addTask(Task task) {
        Result result = new Result();
        try {
            Integer recruitId = task.getRecruitId();
            if(recruitId == null){
                result.setCode(StatusCode.ERROR);
                result.setMessage("招聘id不能为空");
                return result;
            }
            Optional<Recruit> optionalRecruit = recruitDao.findById(recruitId);
            if(!optionalRecruit.isPresent()){
                result.setCode(StatusCode.ERROR);
                result.setMessage("该招聘不存在");
                return result;
            }
            Task selectCountTask = new Task();
            selectCountTask.setRecruitId(task.getRecruitId());
            Example<Task> example = Example.of(selectCountTask);
            long count = taskDao.count(example);
            task.setUpdateTime(new Date());
            task.setCreateTime(new Date());
            count ++;
            task.setSerialNumber((int) count);
            taskDao.save(task);
            result.setCode(StatusCode.OK);
            result.setMessage("添加任务成功");
        }catch (Exception e){
            log.info("添加任务失败："+task.getRecruitId(),e);
            result.setCode(StatusCode.ERROR);
            result.setMessage("添加任务失败");
        }

        return result;
    }

    @Override
    public Result getAll() {
        Result result = new Result();
        List<Task> list;
        try {
            list = taskDao.findAll();
            result.setCode(StatusCode.OK);
            result.setMessage("获取列表成功");
            result.setData(list);
        }catch (Exception e){
            log.info("获取列表失败",e);
            result.setCode(StatusCode.ERROR);
            result.setMessage("获取列表失败");
        }


        return result;
    }
}
